package com.xoa.service.crm.impl;

import com.itextpdf.kernel.pdf.filters.IFilterHandler;
import com.xoa.dao.crm.*;
import com.xoa.dao.inv.*;
import com.xoa.dao.users.UsersMapper;
import com.xoa.model.crm.*;
import com.xoa.model.inv.OmShipmentExample;
import com.xoa.model.users.Users;
import com.xoa.service.crm.CustomerService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.DateFormat;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by qiyang on 2019/5/23.
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private FollowMapper followMapper;

    @Autowired
    private LinkmanMapper linkmanMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private CrmManagerMapper crmManagerMapper;

    @Autowired
    private CrmRoleMapper crmRoleMapper;


    @Autowired
    private OmShipmentMapper omShipmentMapper;

    @Autowired
    private OmReturnMapper omReturnMapper;

    @Autowired
    private CusRepaymentMapper cusRepaymentMapper;
    @Autowired
    private PoCommodityEnterMapper poCommodityEnterMapper;

    @Override
    public String powerCustomer(CustomerWithBLOBs customerWithBLOBs) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);

        String userId = users.getUserId();
        List<CrmManager> crmManagers = crmManagerMapper.selectByManagerId(users.getUserId());
        if (crmManagers.size() != 0) {
            customerWithBLOBs.setManagerType("1");
        } else {
            customerWithBLOBs.setManagerType("2");
        }

        return customerWithBLOBs.getManagerType();
    }


    /**
     * 查询客户  分页  模糊查询 (我的客户)
     *
     * @return
     */
    @Override
    public List<CustomerWithBLOBs> potentialmeCustomer(Integer page, Integer pageSize, Boolean useFlag, Map map, String export, HttpServletResponse response) {

        if (export == null) {
            export = "0";
        }

        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);

        if ("".equals(map.get("createdTimeStr"))) {
            map.put("createdTimeStr", null);
        }
        if ("".equals(map.get("createdTimeEnd"))) {
            map.put("createdTimeEnd", null);
        }
        List<CustomerWithBLOBs> customers = customerMapper.selectByCondition(map);  //这个返回的是map
        //创建一个list集合
        List<CustomerWithBLOBs> customerMe = new ArrayList<>();  //我这个定义的是list所以他报转换错误

        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);

        String userId = users.getUserId();

        //编辑删除权限
        CrmRole crmRoleEit = crmRoleMapper.selectByeEitUser(userId);
        CrmRole crmRoleDel = crmRoleMapper.selectByDelUser(userId);
        for (CustomerWithBLOBs cust : customers) {
            String usernameByUserId = usersMapper.getUsernameByUserId(cust.getCreator());
            cust.setCreator(usernameByUserId);
            cust.setManagerType("1");
            if (crmRoleEit != null && crmRoleDel != null) {
                cust.setType("0");
            } else if (crmRoleEit == null && crmRoleDel == null) {
                cust.setType("1");
            } else if (crmRoleEit == null && crmRoleDel != null) {
                cust.setType("2");
            } else if (crmRoleEit != null) {
                cust.setType("3");
            }
            //放到customerMe集合中
            customerMe.add(cust);
        }

        for (int i = 0; i < customerMe.size(); i++) {
            for (int j = customerMe.size() - 1; j > i; j--) {
                if (customerMe.get(j).getCustomerNo().equals(customerMe.get(i).getCustomerNo())) {
                    customerMe.remove(j);
                }
            }
        }

        try {
            //导出已签到
            if (export.equals("1")) {

                List<CustomerWithBLOBs> customerWithBLOBs1 = new ArrayList<>();
                for (CustomerWithBLOBs withBLOB : customerMe) {
                    if (withBLOB.getIsDeleted() == 0) {
                        //客户状态
                        String customerStatus = withBLOB.getCustomerStatus();
                        if (customerStatus.equals("01")) {
                            withBLOB.setCustomerStatus("初步接触");
                        } else if (customerStatus.equals("02")) {
                            withBLOB.setCustomerStatus("客户拜访");
                        } else if (customerStatus.equals("03")) {
                            withBLOB.setCustomerStatus("需求沟通");
                        } else if (customerStatus.equals("04")) {
                            withBLOB.setCustomerStatus("方案报价");
                        } else if (customerStatus.equals("05")) {
                            withBLOB.setCustomerStatus("商务谈判");
                        } else if (customerStatus.equals("06")) {
                            withBLOB.setCustomerStatus("签约成功");
                        }
                        //客户来源
                        String customerFrom = withBLOB.getCustomerFrom();
                        if (customerFrom.equals("01")) {
                            withBLOB.setCustomerFrom("广告推广");
                        } else if (customerFrom.equals("02")) {
                            withBLOB.setCustomerFrom("会议营销");
                        } else if (customerFrom.equals("03")) {
                            withBLOB.setCustomerFrom("客户介绍");
                        } else if (customerFrom.equals("04")) {
                            withBLOB.setCustomerFrom("网上搜索");
                        } else if (customerFrom.equals("05")) {
                            withBLOB.setCustomerFrom("渠道拓展");
                        } else if (customerFrom.equals("06")) {
                            withBLOB.setCustomerFrom("伙伴介绍");
                        } else if (customerFrom.equals("07")) {
                            withBLOB.setCustomerFrom("独立开发");
                        } else if (customerFrom.equals("08")) {
                            withBLOB.setCustomerFrom("社群营销");
                        }
                        //客户级别
                        String customerLevel = withBLOB.getCustomerLevel();
                        if (customerLevel.equals("01")) {
                            withBLOB.setCustomerLevel("A类重要客户");
                        } else if (customerLevel.equals("02")) {
                            withBLOB.setCustomerLevel("B类普通客户");
                        } else if (customerLevel.equals("03")) {
                            withBLOB.setCustomerLevel("C类一般客户");
                        } else if (customerLevel.equals("04")) {
                            withBLOB.setCustomerLevel("D类不重要客户");
                        }
                        //客户行业
                        String customerIndustry = withBLOB.getCustomerIndustry();
                        if (customerIndustry.equals("01")) {
                            withBLOB.setCustomerIndustry("农、林、牧、渔业");
                        } else if (customerIndustry.equals("02")) {
                            withBLOB.setCustomerIndustry("采矿业");
                        } else if (customerIndustry.equals("03")) {
                            withBLOB.setCustomerIndustry("制造业");
                        } else if (customerIndustry.equals("04")) {
                            withBLOB.setCustomerIndustry("电力、燃气及水的生产和供应业");
                        } else if (customerIndustry.equals("05")) {
                            withBLOB.setCustomerIndustry("建筑业");
                        } else if (customerIndustry.equals("06")) {
                            withBLOB.setCustomerIndustry("交通运输、仓储和邮政业");
                        } else if (customerIndustry.equals("07")) {
                            withBLOB.setCustomerIndustry("信息传输、计算机服务和软件业");
                        } else if (customerIndustry.equals("08")) {
                            withBLOB.setCustomerIndustry("批发和零售业");
                        } else if (customerIndustry.equals("09")) {
                            withBLOB.setCustomerIndustry("住宿和餐饮业");
                        } else if (customerIndustry.equals("10")) {
                            withBLOB.setCustomerIndustry("金融业");
                        } else if (customerIndustry.equals("11")) {
                            withBLOB.setCustomerIndustry("房地产业");
                        } else if (customerIndustry.equals("12")) {
                            withBLOB.setCustomerIndustry("租赁和商务服务业");
                        } else if (customerIndustry.equals("13")) {
                            withBLOB.setCustomerIndustry("科学研究、技术服务和地质勘查业");
                        } else if (customerIndustry.equals("14")) {
                            withBLOB.setCustomerIndustry("水利、环境和公共设施管理业");
                        } else if (customerIndustry.equals("15")) {
                            withBLOB.setCustomerIndustry("居民服务和其他服务业");
                        } else if (customerIndustry.equals("16")) {
                            withBLOB.setCustomerIndustry("教育");
                        } else if (customerIndustry.equals("17")) {
                            withBLOB.setCustomerIndustry("卫生和社会工作");
                        } else if (customerIndustry.equals("18")) {
                            withBLOB.setCustomerIndustry("文化、体育和娱乐业");
                        } else if (customerIndustry.equals("19")) {
                            withBLOB.setCustomerIndustry("公共管理、社会保障和社会组织");
                        } else if (customerIndustry.equals("20")) {
                            withBLOB.setCustomerIndustry("国际组织");
                        } else if (customerIndustry.equals("21")) {
                            withBLOB.setCustomerIndustry("政务机关、事业单位");
                        }
                        if (withBLOB.getExpectTime() != null) {
                            withBLOB.setExpectTimeStr(DateFormat.getStrDate(withBLOB.getExpectTime()));
                        }

                        customerWithBLOBs1.add(withBLOB);
                    }
                }

                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("客户管理表", 9);
                String[] secondTitles = {"客户名称", "客户经理", "客户状态", "客户来源", "客户级别", "客户行业", "预计成交金额", "预计成交日期", "公司地址", "所在地区（省）",
                        "所在地区 （市）", "电子邮箱", "公司网址", "公司规模", "邮政编码", "年销售额"};


                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

                String[] beanProperty = {"customerName", "customerManager", "customerStatus", "customerFrom", "customerLevel", "customerIndustry", "expectPrice", "expectTimeStr", "address", "province",
                        "city", "email", "website", "scale", "zipCode", "annualSales"};


                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, customerWithBLOBs1, beanProperty);
                ServletOutputStream out = response.getOutputStream();

                String filename = "客户管理表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return customerMe;
    }

    @Override
    public List<CustomerWithBLOBs> potentialCustomerSole(Integer page, Integer pageSize, Boolean useFlag, Map map, String export, HttpServletResponse response) {
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(useFlag);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);

        //创建一个list集合
        List<CustomerWithBLOBs> customerMe = new ArrayList<>();
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);

        //编辑删除权限
        CrmRole crmRoleEit = crmRoleMapper.selectByeEitUser(users.getUserId());
        CrmRole crmRoleDel = crmRoleMapper.selectByDelUser(users.getUserId());

        List<CustomerWithBLOBs> customerWithBLOBs = customerMapper.selectByConditionSole(map);
        if (customerWithBLOBs != null) {
            for (CustomerWithBLOBs cust : customerWithBLOBs) {
                String usernameByUserId = usersMapper.getUsernameByUserId(cust.getCreator());
                cust.setCreator(usernameByUserId);
//                                cust.setManagerType("2");
                if (crmRoleEit != null && crmRoleDel != null) {
                    cust.setType("0");
                } else if (crmRoleEit == null && crmRoleDel == null) {
                    cust.setType("4");

                } else if (crmRoleDel != null) {
                    cust.setType("2");

                } else if (crmRoleEit != null) {
                    cust.setType("3");
                }
                //放到customerMe集合中
                customerMe.add(cust);
            }
        }


        for (int i = 0; i < customerMe.size(); i++) {
            for (int j = customerMe.size() - 1; j > i; j--) {
                try {
                    if (customerMe.get(j).getCustomerNo().equals(customerMe.get(i).getCustomerNo())) {
                        customerMe.remove(j);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
        try {
            //导出已签到
            if (export.equals("1")) {

                List<CustomerWithBLOBs> customerWithBLOBs1 = new ArrayList<>();
                for (CustomerWithBLOBs withBLOB : customerMe) {
                    if (withBLOB.getIsDeleted() == 0) {
                        //客户状态
                        String customerStatus = withBLOB.getCustomerStatus();
                        if (customerStatus.equals("01")) {
                            withBLOB.setCustomerStatus("初步接触");
                        } else if (customerStatus.equals("02")) {
                            withBLOB.setCustomerStatus("客户拜访");
                        } else if (customerStatus.equals("03")) {
                            withBLOB.setCustomerStatus("需求沟通");
                        } else if (customerStatus.equals("04")) {
                            withBLOB.setCustomerStatus("方案报价");
                        } else if (customerStatus.equals("05")) {
                            withBLOB.setCustomerStatus("商务谈判");
                        } else if (customerStatus.equals("06")) {
                            withBLOB.setCustomerStatus("签约成功");
                        }
                        //客户来源
                        String customerFrom = withBLOB.getCustomerFrom();
                        if (customerFrom.equals("01")) {
                            withBLOB.setCustomerFrom("广告推广");
                        } else if (customerFrom.equals("02")) {
                            withBLOB.setCustomerFrom("会议营销");
                        } else if (customerFrom.equals("03")) {
                            withBLOB.setCustomerFrom("客户介绍");
                        } else if (customerFrom.equals("04")) {
                            withBLOB.setCustomerFrom("网上搜索");
                        } else if (customerFrom.equals("05")) {
                            withBLOB.setCustomerFrom("渠道拓展");
                        } else if (customerFrom.equals("06")) {
                            withBLOB.setCustomerFrom("伙伴介绍");
                        } else if (customerFrom.equals("07")) {
                            withBLOB.setCustomerFrom("独立开发");
                        } else if (customerFrom.equals("08")) {
                            withBLOB.setCustomerFrom("社群营销");
                        }
                        //客户级别
                        String customerLevel = withBLOB.getCustomerLevel();
                        if (customerLevel.equals("01")) {
                            withBLOB.setCustomerLevel("A类重要客户");
                        } else if (customerLevel.equals("02")) {
                            withBLOB.setCustomerLevel("B类普通客户");
                        } else if (customerLevel.equals("03")) {
                            withBLOB.setCustomerLevel("C类一般客户");
                        } else if (customerLevel.equals("04")) {
                            withBLOB.setCustomerLevel("D类不重要客户");
                        }
                        //客户行业
                        String customerIndustry = withBLOB.getCustomerIndustry();
                        if (customerIndustry.equals("01")) {
                            withBLOB.setCustomerIndustry("农、林、牧、渔业");
                        } else if (customerIndustry.equals("02")) {
                            withBLOB.setCustomerIndustry("采矿业");
                        } else if (customerIndustry.equals("03")) {
                            withBLOB.setCustomerIndustry("制造业");
                        } else if (customerIndustry.equals("04")) {
                            withBLOB.setCustomerIndustry("电力、燃气及水的生产和供应业");
                        } else if (customerIndustry.equals("05")) {
                            withBLOB.setCustomerIndustry("建筑业");
                        } else if (customerIndustry.equals("06")) {
                            withBLOB.setCustomerIndustry("交通运输、仓储和邮政业");
                        } else if (customerIndustry.equals("07")) {
                            withBLOB.setCustomerIndustry("信息传输、计算机服务和软件业");
                        } else if (customerIndustry.equals("08")) {
                            withBLOB.setCustomerIndustry("批发和零售业");
                        } else if (customerIndustry.equals("09")) {
                            withBLOB.setCustomerIndustry("住宿和餐饮业");
                        } else if (customerIndustry.equals("10")) {
                            withBLOB.setCustomerIndustry("金融业");
                        } else if (customerIndustry.equals("11")) {
                            withBLOB.setCustomerIndustry("房地产业");
                        } else if (customerIndustry.equals("12")) {
                            withBLOB.setCustomerIndustry("租赁和商务服务业");
                        } else if (customerIndustry.equals("13")) {
                            withBLOB.setCustomerIndustry("科学研究、技术服务和地质勘查业");
                        } else if (customerIndustry.equals("14")) {
                            withBLOB.setCustomerIndustry("水利、环境和公共设施管理业");
                        } else if (customerIndustry.equals("15")) {
                            withBLOB.setCustomerIndustry("居民服务和其他服务业");
                        } else if (customerIndustry.equals("16")) {
                            withBLOB.setCustomerIndustry("教育");
                        } else if (customerIndustry.equals("17")) {
                            withBLOB.setCustomerIndustry("卫生和社会工作");
                        } else if (customerIndustry.equals("18")) {
                            withBLOB.setCustomerIndustry("文化、体育和娱乐业");
                        } else if (customerIndustry.equals("19")) {
                            withBLOB.setCustomerIndustry("公共管理、社会保障和社会组织");
                        } else if (customerIndustry.equals("20")) {
                            withBLOB.setCustomerIndustry("国际组织");
                        } else if (customerIndustry.equals("21")) {
                            withBLOB.setCustomerIndustry("政务机关、事业单位");
                        }
                        customerWithBLOBs1.add(withBLOB);
                    }
                }

                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("客户管理表", 9);
                String[] secondTitles = {"客户名称", "客户经理", "客户状态", "客户来源", "客户级别", "客户行业", "预计成交金额", "预计成交日期", "公司地址", "所在地区（省）",
                        "所在地区 （市）", "电子邮箱", "公司网址", "公司规模", "邮政编码", "年销售额"};


                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

                String[] beanProperty = {"customerName", "customerManager", "customerStatus", "customerFrom", "customerLevel", "customerIndustry", "expectPrice", "expectTime", "address", "province",
                        "city", "email", "website", "scale", "zipCode", "annualSales"};


                HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, customerWithBLOBs1, beanProperty);
                ServletOutputStream out = response.getOutputStream();

                String filename = "客户管理表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return customerMe;
    }

    @Override
    public List<CustomerWithBLOBs> CustomerSoles(Integer page, Integer pageSize, Map map,HttpServletResponse response) {
        PageParams pageParams = new PageParams();
        pageParams.setUseFlag(false);
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        map.put("page", pageParams);

        //创建一个list集合
        List<CustomerWithBLOBs> customerMe = new ArrayList<>();
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);

        //编辑删除权限
        CrmRole crmRoleEit = crmRoleMapper.selectByeEitUser(users.getUserId());
        CrmRole crmRoleDel = crmRoleMapper.selectByDelUser(users.getUserId());

        List<CustomerWithBLOBs> customerWithBLOBs = customerMapper.selectByConditionSole(map);
        if (customerWithBLOBs != null) {
            for (CustomerWithBLOBs cust : customerWithBLOBs) {
                String usernameByUserId = usersMapper.getUsernameByUserId(cust.getCreator());
                cust.setCreator(usernameByUserId);
//                                cust.setManagerType("2");
                if (crmRoleEit != null && crmRoleDel != null) {
                    cust.setType("0");
                } else if (crmRoleEit == null && crmRoleDel == null) {
                    cust.setType("4");

                } else if (crmRoleDel != null) {
                    cust.setType("2");

                } else if (crmRoleEit != null) {
                    cust.setType("3");
                }
                //放到customerMe集合中
                customerMe.add(cust);
            }
        }


        for (int i = 0; i < customerMe.size(); i++) {
            for (int j = customerMe.size() - 1; j > i; j--) {
                try {
                    if (customerMe.get(j).getCustomerNo().equals(customerMe.get(i).getCustomerNo())) {
                        customerMe.remove(j);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        }
        return customerMe;
    }
    /**
     * 添加客户
     *
     * @return
     */
    @Override
    public int insert(CustomerWithBLOBs customerWithBLOBs) {
        //客户编号
        String number = "";
        //截取时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
        String format = dateFormat.format(date);

        //查询最后一条数据返回一个实体类
        CustomerWithBLOBs customerWithBLOBs1 = customerMapper.selectNo();
        Integer idNum = 0;

        if (customerWithBLOBs1 != null) {

            Integer customerId = customerWithBLOBs1.getCustomerId();
            idNum = customerId + 1;
            String isNumStr = idNum + "";
            if (isNumStr.length() == 1) {
                number = "00000" + isNumStr;
            } else if (isNumStr.length() == 2) {
                number = "0000" + isNumStr;
            } else if (isNumStr.length() == 3) {
                number = "000" + isNumStr;
            } else if (isNumStr.length() == 4) {
                number = "00" + isNumStr;
            } else if (isNumStr.length() == 5) {
                number = "0" + isNumStr;
            } else if (isNumStr.length() == 6) {
                number = isNumStr;
            }
        } else {
            number = "000001";
        }
        String str = "C" + format + number;

        //创建时间
        customerWithBLOBs.setCreatedTime(date);

        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        //创建人
        customerWithBLOBs.setCreator(users.getUserId());
        //默认为未删除
        customerWithBLOBs.setIsDeleted(Byte.valueOf("0"));
        //添加客户编号
        customerWithBLOBs.setCustomerNo(str);
        //默认只能看我的客户
        customerWithBLOBs.setViewPriv("0");
        return customerMapper.insertSelective(customerWithBLOBs);
    }

    /*
     * 添加联系人
     * */
    @Override
    public int insertLinkMan(Linkman linkman) {
        String email = linkman.getEmail();
        linkman.setLinkEmail(email);
        linkman.setCreateTime(new Date());
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        //创建人
        linkman.setCreator(users.getUserId());
        return linkmanMapper.insertSelective(linkman);
    }


    /**
     * 删除客户
     *
     * @param customerId
     * @return
     */
    @Override
    public int deleteByPrimaryKey(Integer customerId) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        CustomerWithBLOBs customerWithBLOBs = customerMapper.selectByPrimaryKey(customerId);
        //删除时间
        customerWithBLOBs.setDeleteTime(new Date());
        //删除人
        customerWithBLOBs.setDeleteUser(users.getUserId());
        //删除状态
        customerWithBLOBs.setIsDeleted(Byte.valueOf("1"));
        return customerMapper.updateByPrimaryKey(customerWithBLOBs);
    }

    /**
     * 编辑回显数据
     *
     * @param customerId
     * @return
     */
    @Override
    public CustomerWithBLOBs selectByPrimaryKey(Integer customerId) {
        CustomerWithBLOBs customerWithBLOBs = customerMapper.selectByPrimaryKey(customerId);
        return customerWithBLOBs;
    }

    /**
     * 编辑客户管理
     *
     * @param customer
     * @return
     */
    @Override
    public int updateByPrimaryKeyWithBLOBs(CustomerWithBLOBs customer) {
        //更新时间
        customer.setUpdatedTime(new Date());
        //更新人
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        customer.setUpdator(users.getUserId());
        return customerMapper.updateByPrimaryKey(customer);
    }

    /**
     * 查询跟进
     */
    @Override
    public List<Follow> findAllFollow(Map map) {


        return followMapper.selectByFollow(map);

    }


    /**
     * 添加跟进
     *
     * @param follow
     * @return
     */
    @Override
    public int insertFollow(Follow follow) {

        //跟进编号
        String number = "";
        //截取时间
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
        String format = dateFormat.format(date);

        //查询最后一条数据返回一个实体类
        Follow follow1 = followMapper.selecFollowtNo();
        Integer idNum = 0;
        if (follow1 != null) {

            Integer followId = follow1.getFollowId();
            idNum = followId + 1;
            String isNumStr = idNum + "";

            if (isNumStr.length() == 1) {
                number = "00000" + isNumStr;
            } else if (isNumStr.length() == 2) {
                number = "0000" + isNumStr;
            } else if (isNumStr.length() == 3) {
                number = "000" + isNumStr;
            } else if (isNumStr.length() == 4) {
                number = "00" + isNumStr;
            } else if (isNumStr.length() == 5) {
                number = "0" + isNumStr;
            } else if (isNumStr.length() == 6) {
                number = isNumStr;
            }

        }
        String str = "F" + format + number;
        //添加客户编号
        follow.setFollowNo(str);
        //添加跟进时间
        follow.setFollowTime(date);

        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        //添加创建人
        follow.setCreator(users.getUserId());
        //添加创建时间
        follow.setCreateTime(date);
        //默认为未删除
        follow.setViewPriv(Byte.valueOf("0"));
        return followMapper.insertSelective(follow);
    }

    /**
     * 删除跟进
     *
     * @param followId
     * @return
     */
    @Override
    public int deleteFollow(Integer followId) {
        //获取登录用户
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
        Follow follow = followMapper.selectByPrimaryKey(followId);
        Date date = new Date();

        //删除时间
        follow.setDeleteTime(date);
        //删除人
        follow.setDeleteUser(users.getUserId());
        //删除状态
        follow.setIsDeleted(Byte.valueOf("1"));
        return followMapper.updateByPrimaryKey(follow);
    }


    /**
     * 方法介绍:   查询和导出接口
     * 参数说明:   @param  user,sortType,isExport
     * 参数说明:  ceshi
     *
     * @return ToJson 返回用户信息
     */
    @Override
    public ToJson<CustomerWithBLOBs> customerExport(HttpServletRequest request, HttpServletResponse response) {
        ToJson<CustomerWithBLOBs> json = new ToJson<>();

        try {

            CustomerExample example = new CustomerExample();
            List<CustomerWithBLOBs> customerWithBLOBs = customerMapper.selectByExampleWithBLOBs(example);
            List<CustomerWithBLOBs> customerWithBLOBs1 = new ArrayList<>();
            for (CustomerWithBLOBs withBLOB : customerWithBLOBs) {
                if (withBLOB.getIsDeleted() == 0) {
                    //客户状态
                    String customerStatus = withBLOB.getCustomerStatus();
                    if (customerStatus.equals("01")) {
                        withBLOB.setCustomerStatus("初步接触");
                    } else if (customerStatus.equals("02")) {
                        withBLOB.setCustomerStatus("客户拜访");
                    } else if (customerStatus.equals("03")) {
                        withBLOB.setCustomerStatus("需求沟通");
                    } else if (customerStatus.equals("04")) {
                        withBLOB.setCustomerStatus("方案报价");
                    } else if (customerStatus.equals("05")) {
                        withBLOB.setCustomerStatus("商务谈判");
                    } else if (customerStatus.equals("06")) {
                        withBLOB.setCustomerStatus("签约成功");
                    }
                    //客户来源
                    String customerFrom = withBLOB.getCustomerFrom();
                    if (customerFrom.equals("01")) {
                        withBLOB.setCustomerFrom("广告推广");
                    } else if (customerFrom.equals("02")) {
                        withBLOB.setCustomerFrom("会议营销");
                    } else if (customerFrom.equals("03")) {
                        withBLOB.setCustomerFrom("客户介绍");
                    } else if (customerFrom.equals("04")) {
                        withBLOB.setCustomerFrom("网上搜索");
                    } else if (customerFrom.equals("05")) {
                        withBLOB.setCustomerFrom("渠道拓展");
                    } else if (customerFrom.equals("06")) {
                        withBLOB.setCustomerFrom("伙伴介绍");
                    } else if (customerFrom.equals("07")) {
                        withBLOB.setCustomerFrom("独立开发");
                    } else if (customerFrom.equals("08")) {
                        withBLOB.setCustomerFrom("社群营销");
                    }
                    //客户级别
                    String customerLevel = withBLOB.getCustomerLevel();
                    if (customerLevel.equals("01")) {
                        withBLOB.setCustomerLevel("A类重要客户");
                    } else if (customerLevel.equals("02")) {
                        withBLOB.setCustomerLevel("B类普通客户");
                    } else if (customerLevel.equals("03")) {
                        withBLOB.setCustomerLevel("C类一般客户");
                    } else if (customerLevel.equals("04")) {
                        withBLOB.setCustomerLevel("D类不重要客户");
                    }
                    //客户行业
                    String customerIndustry = withBLOB.getCustomerIndustry();
                    if (customerIndustry.equals("01")) {
                        withBLOB.setCustomerIndustry("农、林、牧、渔业");
                    } else if (customerIndustry.equals("02")) {
                        withBLOB.setCustomerIndustry("采矿业");
                    } else if (customerIndustry.equals("03")) {
                        withBLOB.setCustomerIndustry("制造业");
                    } else if (customerIndustry.equals("04")) {
                        withBLOB.setCustomerIndustry("电力、燃气及水的生产和供应业");
                    } else if (customerIndustry.equals("05")) {
                        withBLOB.setCustomerIndustry("建筑业");
                    } else if (customerIndustry.equals("06")) {
                        withBLOB.setCustomerIndustry("交通运输、仓储和邮政业");
                    } else if (customerIndustry.equals("07")) {
                        withBLOB.setCustomerIndustry("信息传输、计算机服务和软件业");
                    } else if (customerIndustry.equals("08")) {
                        withBLOB.setCustomerIndustry("批发和零售业");
                    } else if (customerIndustry.equals("09")) {
                        withBLOB.setCustomerIndustry("住宿和餐饮业");
                    } else if (customerIndustry.equals("10")) {
                        withBLOB.setCustomerIndustry("金融业");
                    } else if (customerIndustry.equals("11")) {
                        withBLOB.setCustomerIndustry("房地产业");
                    } else if (customerIndustry.equals("12")) {
                        withBLOB.setCustomerIndustry("租赁和商务服务业");
                    } else if (customerIndustry.equals("13")) {
                        withBLOB.setCustomerIndustry("科学研究、技术服务和地质勘查业");
                    } else if (customerIndustry.equals("14")) {
                        withBLOB.setCustomerIndustry("水利、环境和公共设施管理业");
                    } else if (customerIndustry.equals("15")) {
                        withBLOB.setCustomerIndustry("居民服务和其他服务业");
                    } else if (customerIndustry.equals("16")) {
                        withBLOB.setCustomerIndustry("教育");
                    } else if (customerIndustry.equals("17")) {
                        withBLOB.setCustomerIndustry("卫生和社会工作");
                    } else if (customerIndustry.equals("18")) {
                        withBLOB.setCustomerIndustry("文化、体育和娱乐业");
                    } else if (customerIndustry.equals("19")) {
                        withBLOB.setCustomerIndustry("公共管理、社会保障和社会组织");
                    } else if (customerIndustry.equals("20")) {
                        withBLOB.setCustomerIndustry("国际组织");
                    } else if (customerIndustry.equals("21")) {
                        withBLOB.setCustomerIndustry("政务机关、事业单位");
                    }
                    customerWithBLOBs1.add(withBLOB);
                }
            }
            HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("客户管理表", 9);
            String[] secondTitles = {"客户名称", "客户经理", "客户状态", "客户来源", "客户级别", "客户行业", "预计成交金额", "预计成交日期", "公司地址", "所在地区（省）",
                    "所在地区 （市）", "电子邮箱", "公司网址", "公司规模", "邮政编码", "年销售额"};


            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);

            String[] beanProperty = {"customerName", "customerManager", "customerStatus", "customerFrom", "customerLevel", "customerIndustry", "expectPrice", "expectTime", "address", "province",
                    "city", "email", "website", "scale", "zipCode", "annualSales"};


            HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, customerWithBLOBs1, beanProperty);
            ServletOutputStream out = response.getOutputStream();

            String filename = "客户管理表.xls";
            filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + filename);
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    /**
     * 方法介绍:   插入和导入接口
     * 参数说明:   @param  file
     * 参数说明:
     *
     * @return ToJson 返回用户信息
     */
    @Override
    public ToJson<CustomerWithBLOBs> insertImport(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
        File dest = null;
        ToJson<CustomerWithBLOBs> json = new ToJson<>();
        InputStream in = null;
        try {

            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer stringBuffer = new StringBuffer();
            StringBuffer buffer = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if (uploadPath.indexOf(":") == -1) {
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if (basePath.indexOf("/xoa") != -1) {
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2 = basePath.substring(0, index);
                    }
                    stringBuffer = stringBuffer.append(str2 + "/xoa");
                }
                stringBuffer.append(uploadPath);
                buffer = buffer.append(rb.getString("upload.win"));
            } else {
                stringBuffer = stringBuffer.append(rb.getString("upload.linux"));
                buffer = buffer.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File pathfile = new File(String.valueOf(stringBuffer));
                    if (!pathfile.exists()) {// 如果目录不存在
                        pathfile.mkdirs();// 创建文件夹
                    }
                    dest = new File(stringBuffer.toString(), newFileName);
                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = stringBuffer.append(System.getProperty("file.separator")).append(newFileName).toString();
                    in = new FileInputStream(readPath);
                    HSSFWorkbook workbook = new HSSFWorkbook(in);
                    HSSFSheet sheet = workbook.getSheetAt(0);

                    //3、读取行
                    if (sheet.getPhysicalNumberOfRows() > 5) {
                        CustomerWithBLOBs customer = null;
                        for (int k = 5; k < sheet.getPhysicalNumberOfRows(); k++) {
                            //4、读取单元格
                            HSSFRow row = sheet.getRow(k);
                            customer = new CustomerWithBLOBs();
                            //客户名称
                            Cell cell0 = row.getCell(0);
                            customer.setCustomerName(cell0.getStringCellValue());
                            //客户经理
                            Cell cell1 = row.getCell(1);
                            if (cell1 != null) {
                                customer.setCustomerManager(cell1.getStringCellValue());
                            }
                            //客户状态
                            Cell cell2 = row.getCell(2);
                            String stringCellValue = cell2.getStringCellValue();
                            if (stringCellValue.equals("初步接触")) {
                                customer.setCustomerStatus("01");
                            } else if (stringCellValue.equals("客户拜访")) {
                                customer.setCustomerStatus("02");
                            } else if (stringCellValue.equals("需求沟通")) {
                                customer.setCustomerStatus("03");
                            } else if (stringCellValue.equals("方案报价")) {
                                customer.setCustomerStatus("04");
                            } else if (stringCellValue.equals("商务谈判")) {
                                customer.setCustomerStatus("05");
                            } else if (stringCellValue.equals("签约成功")) {
                                customer.setCustomerStatus("06");
                            }
                            //客户来源
                            Cell cell3 = row.getCell(3);
                            String stringCellValue1 = cell3.getStringCellValue();
                            if (stringCellValue1.equals("广告推广")) {
                                customer.setCustomerFrom("01");
                            } else if (stringCellValue1.equals("会议营销")) {
                                customer.setCustomerFrom("02");
                            } else if (stringCellValue1.equals("客户介绍")) {
                                customer.setCustomerFrom("03");
                            } else if (stringCellValue1.equals("网上搜索")) {
                                customer.setCustomerFrom("04");
                            } else if (stringCellValue1.equals("渠道拓展")) {
                                customer.setCustomerFrom("05");
                            } else if (stringCellValue1.equals("伙伴介绍")) {
                                customer.setCustomerFrom("06");
                            } else if (stringCellValue1.equals("独立开发")) {
                                customer.setCustomerFrom("07");
                            } else if (stringCellValue1.equals("社群营销")) {
                                customer.setCustomerFrom("08");
                            }

                            //客户级别
                            Cell cell4 = row.getCell(4);
                            String stringCellValue2 = cell4.getStringCellValue();
                            if (stringCellValue2.equals("A类重要客户")) {
                                customer.setCustomerLevel("01");
                            } else if (stringCellValue2.equals("B类普通客户")) {
                                customer.setCustomerLevel("02");
                            } else if (stringCellValue2.equals("C类一般客户")) {
                                customer.setCustomerLevel("03");
                            } else if (stringCellValue2.equals("D类不重要客户")) {
                                customer.setCustomerLevel("04");
                            }
                            //客户行业
                            Cell cell5 = row.getCell(5);
                            String stringCellValue3 = cell5.getStringCellValue();
                            if (stringCellValue3.equals("农、林、牧、渔业")) {
                                customer.setCustomerIndustry("01");
                            } else if (stringCellValue3.equals("采矿业")) {
                                customer.setCustomerIndustry("02");
                            } else if (stringCellValue3.equals("制造业")) {
                                customer.setCustomerIndustry("03");
                            } else if (stringCellValue3.equals("电力、燃气及水的生产和供应业")) {
                                customer.setCustomerIndustry("04");
                            } else if (stringCellValue3.equals("建筑业")) {
                                customer.setCustomerIndustry("05");
                            } else if (stringCellValue3.equals("交通运输、仓储和邮政业")) {
                                customer.setCustomerIndustry("06");
                            } else if (stringCellValue3.equals("信息传输、计算机服务和软件业")) {
                                customer.setCustomerIndustry("07");
                            } else if (stringCellValue3.equals("批发和零售业")) {
                                customer.setCustomerIndustry("08");
                            } else if (stringCellValue3.equals("住宿和餐饮业")) {
                                customer.setCustomerIndustry("09");
                            } else if (stringCellValue3.equals("金融业")) {
                                customer.setCustomerIndustry("10");
                            } else if (stringCellValue3.equals("房地产业")) {
                                customer.setCustomerIndustry("11");
                            } else if (stringCellValue3.equals("租赁和商务服务业")) {
                                customer.setCustomerIndustry("12");
                            } else if (stringCellValue3.equals("科学研究、技术服务和地质勘查业")) {
                                customer.setCustomerIndustry("13");
                            } else if (stringCellValue3.equals("水利、环境和公共设施管理业")) {
                                customer.setCustomerIndustry("14");
                            } else if (stringCellValue3.equals("居民服务和其他服务业")) {
                                customer.setCustomerIndustry("15");
                            } else if (stringCellValue3.equals("教育")) {
                                customer.setCustomerIndustry("16");
                            }

                            //预计成交金额
//                            Cell cell6=row.getCell(6);
//                            customer.setExpectPrice(cell6.getStringCellValue());
                            //预计成交日期
//                            Cell cell7=row.getCell(7);
//                            customer.setExpectTime(cell7.getDateCellValue());
                            //公司地址
                            Cell cell6 = row.getCell(6);
                            if (cell6 != null) {
                                customer.setAddress(cell6.getStringCellValue());
                            }
//                            //所在地区（省）
//                            Cell cell9=row.getCell(8);
//                            customer.setProvince(cell9.getStringCellValue());
//                            //所在地区（市）
//                            Cell cell10=row.getCell(9);
//                            customer.setCity(cell10.getStringCellValue());
                            //电子邮箱
                            Cell cell7 = row.getCell(7);
                            if (cell7 != null) {
                                customer.setEmail(cell7.getStringCellValue());
                            }
                            //公司网址
                            Cell cell8 = row.getCell(8);
                            if (cell8 != null) {
                                customer.setWebsite(cell8.getStringCellValue());
                            }
                            //公司规模
                            Cell cell9 = row.getCell(9);
                            if (cell9 != null) {
                                String stringCellValue4 = cell9.getStringCellValue();
                                if (stringCellValue4.equals("微型(10人以下)")) {
                                    customer.setScale("01");
                                } else if (stringCellValue4.equals("小型(10-100人)")) {
                                    customer.setScale("02");
                                } else if (stringCellValue4.equals("中型(500-1000人)")) {
                                    customer.setScale("03");
                                } else if (stringCellValue4.equals("中小型(100-500人)")) {
                                    customer.setScale("04");
                                } else if (stringCellValue4.equals("大型(1000人以上)")) {
                                    customer.setScale("05");
                                }
                            }

                            //邮政编码
                            Cell cell10 = row.getCell(10);
                            if (cell0 != null) {
                                double numericCellValue = cell10.getNumericCellValue();
                                customer.setZipCode(String.valueOf(numericCellValue));
                            }
                            //年销售额
                            Cell cell11 = row.getCell(11);
                            if (cell11 != null) {
                                double numericCellValue1 = cell11.getNumericCellValue();
                                customer.setAnnualSales(String.valueOf(numericCellValue1));
                            }

                            //客户类别
                            Cell cell12 = row.getCell(12);
                            if (cell12 != null) {
                                String stringCellValue5 = cell12.getStringCellValue();
                                if (stringCellValue5.equals("潜在客户")) {
                                    customer.setCustomerType("1");
                                } else if (stringCellValue5.equals("正式客户")) {
                                    customer.setCustomerType("2");
                                } else if (stringCellValue5.equals("重要客户")) {
                                    customer.setCustomerType("3");
                                }
                            }

                            customer.setIsDeleted(Byte.valueOf("0"));
                            customer.setCreatedTime(new Date());
                            //获取登录用户
                            HttpServletRequest request1 = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
                            Cookie redisSessionCookie = CookiesUtil.getCookieByName(request1, "redisSessionId");
                            Users users = SessionUtils.getSessionInfo(request1.getSession(), Users.class, new Users(), redisSessionCookie);
                            //创建人
                            customer.setCreator(users.getUserId());
                            //客户编号
                            String number = "";
                            //截取时间
                            Date date = new Date();
                            SimpleDateFormat dateFormat = new SimpleDateFormat("yyMMdd");
                            String format = dateFormat.format(date);

                            //查询最后一条数据返回一个实体类
                            CustomerWithBLOBs customerWithBLOBs1 = customerMapper.selectNo();
                            Integer idNum = 0;

                            if (customerWithBLOBs1 != null) {

                                Integer customerId = customerWithBLOBs1.getCustomerId();
                                idNum = customerId + 1;
                                String isNumStr = idNum + "";
                                if (isNumStr.length() == 1) {
                                    number = "00000" + isNumStr;
                                } else if (isNumStr.length() == 2) {
                                    number = "0000" + isNumStr;
                                } else if (isNumStr.length() == 3) {
                                    number = "000" + isNumStr;
                                } else if (isNumStr.length() == 4) {
                                    number = "00" + isNumStr;
                                } else if (isNumStr.length() == 5) {
                                    number = "0" + isNumStr;
                                } else if (isNumStr.length() == 6) {
                                    number = isNumStr;
                                }
                            }
                            String str = "C" + format + number;
                            customer.setCustomerNo(str);
                            customer.setViewPriv("0");
                            //5、保存用户
                            customerMapper.insertSelective(customer);
                            Integer customerId = customer.getCustomerId();

                            Linkman linkman = new Linkman();
                            linkman.setCustomerId(customerId);
                            //联系人
                            Cell cell13 = row.getCell(13);
                            String stringCellValue6 = cell13.getStringCellValue();
                            if (stringCellValue6 != null) {
                                linkman.setLinkmanName(stringCellValue6);
                            } else {
                                linkman.setLinkmanName("");
                            }

                            Cell cell14 = row.getCell(14);
                            if (cell14 != null) {
                                String stringCellValue7 = cell14.getStringCellValue();
                                if (stringCellValue7.equals("电话")) {
                                    linkman.setFirstContact("01");
                                } else if (stringCellValue7.equals("邮件")) {
                                    linkman.setFirstContact("02");
                                } else if (stringCellValue7.equals("微信")) {
                                    linkman.setFirstContact("03");
                                } else if (stringCellValue7.equals("QQ")) {
                                    linkman.setFirstContact("04");
                                } else if (stringCellValue7.equals("短信")) {
                                    linkman.setFirstContact("05");
                                } else {
                                    linkman.setFirstContact("");
                                }
                            }
                            //联系人性别
                            Cell cell15 = row.getCell(15);
                            if(cell15 != null){
                                String stringCellValue15 = cell15.getStringCellValue();
                                if (stringCellValue15 != null &&stringCellValue15 != "") {
                                    if (stringCellValue15.equals("男")) {
                                        linkman.setSex(Byte.valueOf("1"));
                                    } else if (stringCellValue15.equals("女")) {
                                        linkman.setSex(Byte.valueOf("2"));
                                    }
                                } else {
                                    linkman.setSex(Byte.valueOf("0"));
                                }
                            }
                            //联系人职务
                            Cell cell16 = row.getCell(16);
                            if(cell16 != null){
                                String stringCellValue16 = cell16.getStringCellValue();
                                if (stringCellValue16 != null&&stringCellValue16 !="") {
                                    linkman.setJob(stringCellValue16);
                                } else {
                                    linkman.setJob("");
                                }
                            }

                            //联系人部门
                            Cell cell17 = row.getCell(17);
                            if(cell17 != null){
                                String stringCellValue17 = cell17.getStringCellValue();
                                if (stringCellValue17 != null&&stringCellValue17 !="") {
                                    linkman.setDepartment(stringCellValue17);
                                } else {
                                    linkman.setDepartment("");
                                }
                            }

                            //联系人邮箱
                            Cell cell18 = row.getCell(18);
                            if(cell18 != null){
                                String stringCellValue18 = cell18.getStringCellValue();
                                if (stringCellValue18 != null &&stringCellValue18 !="") {
                                    linkman.setEmail(stringCellValue18);
                                } else {
                                    linkman.setEmail("");
                                }
                            }

                            //联系人手机
                            Cell cell19 = row.getCell(19);
                            if (cell19 != null) {
                                int stringCellValue19 = (int) cell19.getNumericCellValue();
                                linkman.setMobile(String.valueOf(stringCellValue19));
                            }
                            //联系人微信
                            Cell cell20 = row.getCell(20);
                            if (cell20 != null) {
                                String s = cell20.getCellType().toString();
                                if (s.endsWith("NUMERIC")) {
                                    int stringCellValue20 = (int) cell20.getNumericCellValue();
                                    linkman.setWechat(String.valueOf(stringCellValue20));
                                } else {
                                    String stringCellValue20 = (String) cell20.getStringCellValue();
                                    linkman.setWechat(stringCellValue20);
                                }
                            }

                            //联系人QQ
                            Cell cell21 = row.getCell(21);
                            if (cell21 != null) {
                                int stringCellValue21 = (int) cell21.getNumericCellValue();
                                linkman.setQq(String.valueOf(stringCellValue21));
                            }

                            //联系人备注
                            Cell cell22 = row.getCell(22);
                            if(cell22!=null){
                                String stringCellValue22 = cell22.getStringCellValue();
                                if (stringCellValue22 != null&&stringCellValue22 !="") {
                                    linkman.setRemark(stringCellValue22);
                                } else {
                                    linkman.setRemark("");
                                }
                            }

                            linkmanMapper.insertSelective(linkman);
                        }
                    }

                    json.setFlag(0);
                    json.setMsg("ok");
                    dest.delete();
                } else {
                    json.setMsg("文件类型不正确！");
                    json.setFlag(1);
                    return json;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("数据保存异常");
            json.setFlag(1);
        } finally {
            dest.delete();
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return json;
    }
    //客户利润
    @Override
    public ToJson<Customer> findCustomerProfit(String month,String customerId,String enterId,String year,String day,String page,String limit,
                                               String warehouseId,
                                               String userId) {

        ToJson<Customer> toJson=new ToJson<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String,Object> map1=new HashMap<>();

        PageParams pageParams=new PageParams();
        pageParams.setPage(Integer.parseInt(page));
        pageParams.setPageSize(Integer.parseInt(limit));
        if (!StringUtils.checkNull(year)){
            map1.put("year",year);
        }
        if (!StringUtils.checkNull(month)){
            map1.put("year",month.split("-")[0]);
            map1.put("month",month.split("-")[1]);
        }
        if (!StringUtils.checkNull(day)){
            map1.put("year",day.split("-")[0]);
            map1.put("month",day.split("-")[1]);
            map1.put("day",day.split("-")[2]);
        }
        if (!StringUtils.checkNull(warehouseId)){
            map1.put("warehouseId",warehouseId);
        }
        if (!StringUtils.checkNull(enterId)){
            map1.put("enterId",enterId);
        }
        if (!StringUtils.checkNull(customerId)){
            map1.put("customerId",customerId);
        }
        if (!StringUtils.checkNull(userId)){
            map1.put("userId",userId);
        }
        List<Customer> customers = customerMapper.selectAllCustomer(map1);
        map1.put("pageParams",pageParams);

        // try{
        List<Customer> customerList = customerMapper.selectAllCustomer(map1);
        Set<Integer> set=new HashSet();
        for (Customer customer : customerList) {
            set.add(customer.getCustomerId());
        }
        for (Integer i : set) {

            //System.out.println("customerId:" + customer.getCustomerId());
            Map<String, Object> map = new HashMap<>();

            map.put("CustomerId", i);

            CustomerWithBLOBs customerWithBLOBs = customerMapper.selectByPrimaryKey(i);
            map.put("CustomerName", customerWithBLOBs.getCustomerName());
            map.put("CustomerEmail", customerWithBLOBs.getEmail());
            map.put("CustomerAddress", customerWithBLOBs.getAddress());
            Double enterPrice = poCommodityEnterMapper.selectEnterTotal(map);
            if ("null".equals(enterPrice+"")){
                enterPrice=0.00;
            }
            //出货数量总和
            Integer shipMentCount = customerMapper.shipmentCount(map1);
            //System.out.println("shipMentCount" + shipMentCount);
            //退货数量总和

            Integer returnCount = customerMapper.returnCount(map1);
            //System.out.println("returnCount" + returnCount);
            //销售数量合计
            if(shipMentCount!=null && returnCount!=null){
                Integer SaleCount = shipMentCount - returnCount;
                map.put("SaleCount",SaleCount);
                //System.out.println("SaleCount" + SaleCount);
            }else if(returnCount == null){
                map.put("SaleCount",shipMentCount);
            }
            else{
                map.put("SaleCount",0);
            }

            //销售金额总计 = 销售金额统计-退货金额统计
            Double saleMoney = customerMapper.SaleMoney(map1);
            Double outMoney = customerMapper.OutMoney(map1);

            //Double saleMoneyCount = customerMapper.saleMoneyCount(customer.getCustomerId());

            if (saleMoney != null && outMoney != null){
                double saleMoneyCount = saleMoney-outMoney;
                map.put("SaleMoneyCount", saleMoneyCount);
            }else if(outMoney == null){
                map.put("SaleMoneyCount",saleMoney);
            }else {
                map.put("SaleMoneyCount",0);
            }
            List<OmShipmentExample> list2= omShipmentMapper.selectShipCount(map1);
            //利润总计
            Double realPrice=0.00;

            //销售总计
            Double saleShipPrice=0.00;

            //销售退货总计
            Double saleReturnPrice=0.00;

            for(OmShipmentExample omShipment:list2){
                if ("null".equals(omShipment.getSaleShipPrice()+"")){
                    omShipment.setSaleShipPrice(0);
                }
                if ("null".equals(omShipment.getRealPrice()+"")){
                    omShipment.setRealPrice(0);
                }
                realPrice+=omShipment.getRealPrice();
                saleShipPrice+=omShipment.getSaleShipPrice();
            }
            //退货总计
            List<OmShipmentExample> list1 = omShipmentMapper.selectReturnCount(map1);
            List<OmShipmentExample> lists=new ArrayList<>();
            for (OmShipmentExample omShipmentExample:list1){
                if ("null".equals(omShipmentExample.getSaleReturnPrice()+"")){
                    omShipmentExample.setSaleReturnPrice(0);
                }
                if ("null".equals(omShipmentExample.getRealPrice2()+"")){
                    omShipmentExample.setRealPrice2(0);
                }
                saleReturnPrice+=omShipmentExample.getSaleReturnPrice();
                realPrice-=omShipmentExample.getRealPrice2();
            }
            map.put("realPrice",realPrice);
            map.put("saleShipPrice",saleShipPrice-saleReturnPrice-realPrice);


            //销售成本 = 进货单价*进货数量 - 退货单价*退货数量
            //Double saleCount = customerMapper.SaleCount(customer.getCustomerId());
            //客户利润
            list.add(map);
        }
//            }catch (Exception e){
//                e.getMessage();
//            }
        toJson.setTotleNum(customers.size());
        toJson.setFlag(0);
        toJson.setObject(list);
        return toJson;
    }


    //员工销售业绩
    @Override
    public  ToJson<Users> findEmployeeSales(String month,String customerId,String enterId,String year,String day,String page,String limit,
                                            String warehouseId,
                                            String userId) {
        ToJson<Users> toJson=new ToJson<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String,Object> map2=new HashMap<>();

        PageParams pageParams=new PageParams();
        pageParams.setPage(Integer.parseInt(page));
        pageParams.setPageSize(Integer.parseInt(limit));
        if (!StringUtils.checkNull(year)){
            map2.put("year",year);
        }
        if (!StringUtils.checkNull(month)){
            map2.put("year",month.split("-")[0]);
            map2.put("month",month.split("-")[1]);
        }
        if (!StringUtils.checkNull(day)){
            map2.put("year",day.split("-")[0]);
            map2.put("month",day.split("-")[1]);
            map2.put("day",day.split("-")[2]);
        }
        if (!StringUtils.checkNull(warehouseId)){
            map2.put("warehouseId",warehouseId);
        }
        if (!StringUtils.checkNull(enterId)){
            map2.put("enterId",enterId);
        }
        if (!StringUtils.checkNull(userId)){
            map2.put("userId",userId);
        }
        if (!StringUtils.checkNull(customerId)){
            map2.put("customerId",customerId);
        }
        List<Users> users2 = usersMapper.selectAllUsersName(map2);
        map2.put("pageParams",pageParams);
        List<Users> usersList = usersMapper.selectAllUsersName(map2);

        Set<Integer> set= new HashSet();
        for (Users users : usersList) {
            set.add(users.getUid());
        }

        for (Integer i : set) {

            Map<String, Object> map = new HashMap<>();

            map.put("UserId",i);
            Users users1 = usersMapper.selectUserByUId(i);
            map.put("username",users1.getUserName());

            map2.put("userId",i);
            Map<String,Object> map1=new HashMap<>();

            if (!StringUtils.checkNull(month)){
                map1.put("month",month);
            }
            map1.put("userId",i);

            //出货数量总和
            Integer shipMentCount = omShipmentMapper.shipmentCount(map2);

            //退货数量总和
            Integer returnCount = omReturnMapper.returnCount(map2);

            //销售数量合计
            if(shipMentCount!=null && returnCount!=null){
                Integer SaleCount = shipMentCount - returnCount;
                map.put("SaleCount",SaleCount);
                //System.out.println("SaleCount" + SaleCount);
            }else if(returnCount == null){
                if (shipMentCount==null){
                    shipMentCount=0;
                }
                map.put("SaleCount",shipMentCount);
            }
            else{
                map.put("SaleCount",0);
            }

            //销售金额总计 = 销售金额统计-退货金额统计
            Double saleMoney = omShipmentMapper.SaleMoney(map2);
            Double outMoney = omReturnMapper.OutMoney(map2);

            if (saleMoney != null && outMoney != null){
                double saleMoneyCount = saleMoney-outMoney;
                map.put("SaleMoneyCount", saleMoneyCount);

            }else if(outMoney == null){
                if (saleMoney==null){
                    saleMoney=0.00;
                }
                map.put("SaleMoneyCount",saleMoney);
            }else {
                map.put("SaleMoneyCount",0);
            }


            List<OmShipmentExample> list2= omShipmentMapper.selectShipCount(map2);
            //利润总计
            Double realPrice=0.00;

            //销售总计
            Double saleShipPrice=0.00;

            //销售退货总计
            Double saleReturnPrice=0.00;

            for(OmShipmentExample omShipment:list2){
                if ("null".equals(omShipment.getSaleShipPrice()+"")){
                    omShipment.setSaleShipPrice(0);
                }
                if ("null".equals(omShipment.getRealPrice()+"")){
                    omShipment.setRealPrice(0);
                }
                realPrice+=omShipment.getRealPrice();
                saleShipPrice+=omShipment.getSaleShipPrice();
            }
            //退货总计
            List<OmShipmentExample> list1 = omShipmentMapper.selectReturnCount(map2);
            List<OmShipmentExample> lists=new ArrayList<>();
            for (OmShipmentExample omShipmentExample:list1){
                if ("null".equals(omShipmentExample.getSaleReturnPrice()+"")){
                    omShipmentExample.setSaleReturnPrice(0);
                }
                if ("null".equals(omShipmentExample.getRealPrice2()+"")){
                    omShipmentExample.setRealPrice2(0);
                }
                saleReturnPrice+=omShipmentExample.getSaleReturnPrice();
                realPrice-=omShipmentExample.getRealPrice2();
            }
            map.put("realPrice",realPrice);
            map.put("saleShipPrice",saleShipPrice-saleReturnPrice-realPrice);

            //销售额提成金额

            //员工业绩


            list.add(map);

        }
        toJson.setFlag(0);
        toJson.setTotleNum(users2.size());
        toJson.setObject(list);
        return toJson;
    }

    //员工提成
    @Override
    public ToJson<Users> findEmployeeCommission(String month, String userId,String year,String day,String flag,String price,String warehouseId,String limit,String page) {

        ToJson<Users> toJson=new ToJson<>();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String,Object> map2=new HashMap<>();
        PageParams pageParams=new PageParams();
        pageParams.setPage(Integer.parseInt(page));
        pageParams.setPageSize(Integer.parseInt(limit));
        if (!StringUtils.checkNull(year)){
            map2.put("year",year);
        }
        //按月查询
        if (!StringUtils.checkNull(month)){
            map2.put("year",month.split("-")[0]);
            map2.put("month",month.split("-")[1]);
        }
        //按日查询
        if (!StringUtils.checkNull(day)){
            map2.put("year",day.split("-")[0]);
            map2.put("month",day.split("-")[1]);
            map2.put("day",day.split("-")[2]);
        }
        //按仓库查询
        if (!StringUtils.checkNull(warehouseId)){
            map2.put("warehouseId",warehouseId);
        }
        List<Users> users2 = usersMapper.selectAllUsersName(map2);
        map2.put("pageParams",pageParams);
        List<Users> usersList = usersMapper.selectAllUsersName(map2);

        Set<String> set= new HashSet();
        for (Users users : usersList) {
            set.add(users.getUid()+"");
        }

        for (String i : set) {

            Map<String, Object> map = new HashMap<>();

            map.put("UserId",i);
            Users users1 = usersMapper.selectUserByUId(Integer.parseInt(i));
            map.put("userName",users1.getUserName());


            Map<String,Object> map1=new HashMap<>();
            map2.put("userId",i);
            //出货数量总和
            Integer shipMentCount = omShipmentMapper.shipmentCount(map2);

            //退货数量总和
            Integer returnCount = omReturnMapper.returnCount(map2);

            //销售数量合计
            Integer SaleCount=0;
            if(shipMentCount!=null && returnCount!=null){
                SaleCount = shipMentCount - returnCount;
                map.put("SaleCount",SaleCount);
                //System.out.println("SaleCount" + SaleCount);
            }else if(returnCount == null){
                map.put("SaleCount",shipMentCount);
            }
            else{
                map.put("SaleCount",0);
            }

            //销售金额总计 = 销售金额统计-退货金额统计
            Double saleMoney = omShipmentMapper.SaleMoney(map2);

            Double outMoney = omReturnMapper.OutMoney(map2);
            double saleMoneyCount=0.00;
            if (saleMoney != null && outMoney != null){
                saleMoneyCount = saleMoney-outMoney;
                map.put("SaleMoneyCount", saleMoneyCount);

            }else if(outMoney == null){
                saleMoneyCount=saleMoney;
                map.put("SaleMoneyCount",saleMoney);

            }else {
                saleMoneyCount=0;
                map.put("SaleMoneyCount",0);
            }

            //销售额提成金额

            //员工业绩(利润)

            List<OmShipmentExample> list2= omShipmentMapper.selectShipCount(map2);
            //利润总计
            Double realPrice=0.00;

            //销售总计
            Double saleShipPrice=0.00;

            //销售退货总计
            Double saleReturnPrice=0.00;

            for(OmShipmentExample omShipment:list2){
                if ("null".equals(omShipment.getSaleShipPrice()+"")){
                    omShipment.setSaleShipPrice(0);
                }
                if ("null".equals(omShipment.getRealPrice()+"")){
                    omShipment.setRealPrice(0);
                }
                realPrice+=omShipment.getRealPrice();
                saleShipPrice+=omShipment.getSaleShipPrice();
            }
            //退货总计
            List<OmShipmentExample> list1 = omShipmentMapper.selectReturnCount(map2);
            List<OmShipmentExample> lists=new ArrayList<>();
            for (OmShipmentExample omShipmentExample:list1){
                if ("null".equals(omShipmentExample.getSaleReturnPrice()+"")){
                    omShipmentExample.setSaleReturnPrice(0);
                }
                if ("null".equals(omShipmentExample.getRealPrice2()+"")){
                    omShipmentExample.setRealPrice2(0);
                }
                saleReturnPrice+=omShipmentExample.getSaleReturnPrice();
                realPrice-=omShipmentExample.getRealPrice2();
            }
            map.put("realPrice",realPrice);

            //已付金额合计
            Double amountPaid = omShipmentMapper.amountPaid(map2);
            map.put("AmountMoney",amountPaid);
            if ("null" .equals(amountPaid+"")){
                amountPaid=0.00;
            }
            //还款金额
            Double repaymentAmount = cusRepaymentMapper.repaymentAmount(map2);
            if ("null" .equals(repaymentAmount+"")){
                repaymentAmount=0.00;
            }
            map.put("RepaymentAmount",repaymentAmount);
            //flag   0按销售金额提成 1按已付金额提成  2按销售利润提成  3按销售数量提成  4按还款金额提成
            //提成
            Double tiPrice=0.00;
            if ("0".equals(flag)){
                tiPrice=saleMoneyCount*Double.parseDouble(price);
            }else if ("1".equals(flag)){
                tiPrice=amountPaid*Double.parseDouble(price);
            }else if ("2".equals(flag)){
                tiPrice=realPrice*Double.parseDouble(price);
            }else if ("3".equals(flag)){
                tiPrice=SaleCount*Double.parseDouble(price);
            }else if ("4".equals(flag)){
                tiPrice=repaymentAmount*Double.parseDouble(price);
            }
            DecimalFormat df   = new DecimalFormat("######0.00");
            String format = df.format(tiPrice);
            map.put("tiPrice",format);
            list.add(map);


        }
        toJson.setObject(list);
        toJson.setTotleNum(users2.size());
        toJson.setMsg("OK");
        toJson.setFlag(0);
        return toJson;
    }

}
